#!/usr/bin/python2.4
# -*- python -*-
#
# Copyright (C) 2008  Google, Inc. All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

"""
TsumuFS, a NFS-based caching filesystem.

This file contains the startup code that launches into the FuseThread
class. See that module for more details.
"""

import sys
import syslog
import traceback

import fuse

development_mode = True
if development_mode == True:
  sys.path.append('../lib')

import tsumufs


def syslogExceptHook(type, value, tb):
  """
  Quick exception handler to log exceptions to syslog rather than
  dumping them to /dev/null after FUSE has forked.
  """

  syslog.syslog("*** Unhandled exception occurred")
  syslog.syslog("***     Type: %s" % type)
  syslog.syslog("***    Value: %s" % value)
  syslog.syslog("*** Traceback:")

  for line in traceback.extract_tb(tb):
    syslog.syslog("***    %s(%d) in %s: %s"
                  % line)


def main():
  # Grab the name of this program from the zeroth argument and make
  # sure it's just the last part of the name if there's a path.
  tsumufs.progName = sys.argv[0].split('/')[-1]

  # Verify that we're using a fuse-python version new enough to know
  # about __version__. Bail if otherwise.
  if not hasattr(fuse, '__version__'):
    raise RuntimeError, ('Your fuse-python version is too old. Please '
                         'upgrade to v0.2 at the minimum.')

  # Assert we have initialization and stateful file support in fuse
  # itself.
  fuse.feature_assert('stateful_files', 'has_init')

  # Force the API to use the current version.
  fuse.fuse_python_api = fuse.FUSE_PYTHON_API_VERSION

  # Setup our first thread, and parse our command line options.
  server = tsumufs.FuseThread()
  server.parseCommandLine()

  # Install our custom exception handler so that any exceptions are
  # output to the syslog rather than to /dev/null.
  sys.excepthook = syslogExceptHook

  # Go!
  server.main()

if __name__ == '__main__':
  main()
